package com.colin.aiyi.ui.Home.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.colin.aiyi.R;
import com.colin.aiyi.adapter.MsgAdapter;
import com.colin.aiyi.adapter.OneSayAdapter;
import com.colin.aiyi.adapter.SentenceAdapter;
import com.colin.aiyi.app.Constant;
import com.colin.aiyi.entity.MsgEntity;
import com.colin.aiyi.entity.User;
import com.colin.aiyi.entity.YiJuAndYiShuoEntity;
import com.colin.aiyi.fragment.BaseFragment;
import com.colin.aiyi.ui.login.LoginAc;
import com.colin.aiyi.ui.pay.PayAc;
import com.colin.aiyi.ui.personal.PersonalAc;
import com.colin.aiyi.utils.SharePreferenceUtil;
import com.colin.aiyi.utils.TimeUtil;
import com.colin.aiyi.view.CustomLoadMoreView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * Created by hl on 2017/5/8.
 */

public class HomeFragment2WithNewRefresh extends BaseFragment implements IViewHome {

    @BindView(R.id.imageview)
    ImageView imageview;
    @BindView(R.id.text_name)
    TextView textName;
    @BindView(R.id.dd)
    LinearLayout dd;
    @BindView(R.id.frame_layout)
    FrameLayout frameLayout;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    Unbinder unbinder;
    @BindView(R.id.text_history)
    TextView textHistory;
    @BindView(R.id.text_like)
    TextView textLike;
    @BindView(R.id.text_msg)
    TextView textMsg;
    @BindView(R.id.text_daoshi)
    TextView textDaoshi;
    @BindView(R.id.text_yulu)
    TextView textYulu;

    @BindView(R.id.text_city)
    TextView textCity;
    @BindView(R.id.text_vip)
    TextView textVip;
    @BindView(R.id.text_edit)
    TextView textEdit;
    @BindView(R.id.text_pay)
    TextView textPay;
    @BindView(R.id.text_no_data)
    TextView textNoData;
    @BindView(R.id.text_vip_tag)
    TextView textVipTag;
    @BindView(R.id.text_vip_line)
    LinearLayout textVipLine;
    @BindView(R.id.text_msg_flag)
    TextView textMsgFlag;
    @BindView(R.id.text_msg_parent)
    RelativeLayout textMsgParent;
    @BindView(R.id.fragment_rotate_header_with_text_view_frame)
    PtrClassicFrameLayout hFrame;
    private List<YiJuAndYiShuoEntity> myWordList = new ArrayList<>();
    private List<MsgEntity.ItemsBean> msgList = new ArrayList<>();
    private View tab_home_like;
    private SentenceAdapter sentenceAdapter;
    private OneSayAdapter oneSayAdapter;
    private CustomLoadMoreView customLoadMoreView;
    public static final int HISTORY = 0x1;
    public static final int LIKE = 0x2;
    ImpPHome iPresenter;
    private User user;
    private MsgAdapter msgAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        user = SharePreferenceUtil.getObject(getContext(), User.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home2with_new_refresh, null);
        unbinder = ButterKnife.bind(this, view);
        iPresenter = new ImpPHome(this);
        initView(inflater, view);
        return view;
    }


    @Override
    protected void lazyLoad() {
        if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1) {
            Intent intent = new Intent(getContext(), LoginAc.class);
            intent.putExtra("FromAc", Constant.MIAN);
            startActivity(intent);
            return;
        }
        if (user.getOrderType() == null) {
            setTabSelcect(HISTORY);
        }
        allMsgRead();

    }


    void initView(LayoutInflater inflater, View view) {
        tab_home_like = view.findViewById(R.id.tab_home_like);
        hFrame.setLastUpdateTimeRelateObject(this);
        hFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                iPresenter.onRefresh();
            }
        });
        customLoadMoreView = new CustomLoadMoreView();
        oneSayAdapter = new OneSayAdapter(myWordList, getContext());
        oneSayAdapter.setLoadMoreView(customLoadMoreView);
        oneSayAdapter.setOnItemChildClickListener(iPresenter);
        oneSayAdapter.setOnItemClickListener(iPresenter);

        sentenceAdapter = new SentenceAdapter(myWordList);
        sentenceAdapter.setOnItemChildClickListener(iPresenter);
        sentenceAdapter.setLoadMoreView(customLoadMoreView);

        msgAdapter = new MsgAdapter(msgList);
        msgAdapter.setLoadMoreView(customLoadMoreView);
        msgAdapter.setOnItemClickListener(iPresenter);
        msgAdapter.setOnItemChildClickListener(iPresenter);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setNestedScrollingEnabled(false);
        initHeadView();
    }

    private void initHeadView() {
        if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1) {
            return;
        }
        Glide.with(getContext()).load(Constant.BASE_URL + user.getHeadUrl()).error(R.mipmap.pic2).into(imageview);
        if (user.isVip()) {
            textPay.setText("会员续费");
            textVipLine.getBackground().setLevel(1);
            textVip.setVisibility(View.VISIBLE);
            textVipTag.setTextColor(getResources().getColor(R.color.c666));
            textVipTag.setText(TimeUtil.getTime(user.getVipStart(), TimeUtil.DATE_FORMAT_DATE_YEAR_M_DOT)
                    + "+"
                    + TimeUtil.getTime(user.getVipStart(), TimeUtil.DATE_FORMAT_DATE_YEAR_M_DOT));

        } else {
            textVipLine.getBackground().setLevel(0);
            textVip.setVisibility(View.GONE);
            textVipTag.setText("普通会员");
            textVipTag.setTextColor(getResources().getColor(R.color.white));
        }
        textName.setText(user.getUserName());
        textCity.setText(user.getCityName());

    }


    @OnClick({R.id.text_history, R.id.text_like, R.id.text_msg, R.id.text_daoshi, R.id.text_yulu,
            R.id.text_city, R.id.text_edit, R.id.text_pay, R.id.text_msg_parent})
    void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.text_history:
            case R.id.text_like:
            case R.id.text_msg:
            case R.id.text_msg_parent:
            case R.id.text_daoshi:
            case R.id.text_yulu:
                setTabSelcect(view.getId());
                break;
            case R.id.text_city:
//                intent =new Intent(getContext(),ProvinceAc.class);
                // startActivityForResult(intent,0x3);
                break;
            case R.id.text_edit:
                intent = new Intent(getContext(), PersonalAc.class);
                startActivityForResult(intent, 0x3);
                break;
            case R.id.text_pay:
                intent = new Intent(getContext(), PayAc.class);
                startActivityForResult(intent, 0x3);
                break;
        }

    }

    public void setTabSelcect(int viewid) {
        textHistory.setTextColor(getResources().getColor(R.color.c666));
        textLike.setTextColor(getResources().getColor(R.color.c666));
        textMsg.setTextColor(getResources().getColor(R.color.c666));
        textDaoshi.setTextColor(getResources().getColor(R.color.c3333));
        textYulu.setTextColor(getResources().getColor(R.color.c3333));
        switch (viewid) {
            case HISTORY:
            case R.id.text_history:
                tab_home_like.setVisibility(View.GONE);
                textHistory.setTextColor(getResources().getColor(R.color.black));
                recyclerView.setAdapter(oneSayAdapter);
                user.setPageNum(1);
                user.setOrderType(Constant.TAB_TYPE_SAY_WACTH);
                iPresenter.getAllT(user);
                break;
            case LIKE:
            case R.id.text_like:
                tab_home_like.setVisibility(View.VISIBLE);
                setTabSelcect(R.id.text_daoshi);
                break;
            case R.id.text_msg:
            case R.id.text_msg_parent:
                tab_home_like.setVisibility(View.GONE);
                textMsg.setTextColor(getResources().getColor(R.color.black));
                recyclerView.setAdapter(msgAdapter);
                user.setPageNum(1);
                user.setOrderType(Constant.TAB_TYPE_MSG);
                iPresenter.getAllT(user);
                break;
            case R.id.text_daoshi:
                textLike.setTextColor(getResources().getColor(R.color.black));
                textDaoshi.setTextColor(getResources().getColor(R.color.white));
                recyclerView.setAdapter(oneSayAdapter);
                user.setPageNum(1);
                user.setOrderType(Constant.TAB_TYPE_SAY_LIKE);
                iPresenter.getAllT(user);
                break;
            case R.id.text_yulu:
                textLike.setTextColor(getResources().getColor(R.color.black));
                textYulu.setTextColor(getResources().getColor(R.color.white));
                recyclerView.setAdapter(sentenceAdapter);
                user.setPageNum(1);
                user.setOrderType(Constant.TAB_TYPE_LIKE);
                iPresenter.getAllT(user);
                // iPresenter.getAllT("1", Constant.TAB_TYPE_LIKE);
                break;
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x586) {

            String uname = data.getStringExtra("uname");
            String cname = data.getStringExtra("cname");
            String headimg = data.getStringExtra("headimg");
            textName.setText(uname);
            textCity.setText(cname);
            if (headimg != null) {
                Glide.with(this).load(new File(headimg)).into(imageview);
            }
        }
        if (resultCode == 0x312){
            allMsgRead();
        }
    }

    @Override
    public FragmentManager getFM() {
        return getChildFragmentManager();
    }

    @Override
    public List getData() {
        if (user == null || user.getAccessToken() == null || user.getAccessToken().length() < 1) {
            return myWordList;
        } else {
            if (user.getOrderType() == Constant.TAB_TYPE_MSG) {
                return msgList;
            }
        }
        return myWordList;
    }

    @Override
    public void pullMoreComlite(String... msg) {
        if (user.getOrderType().equals(Constant.TAB_TYPE_LIKE)) {
            sentenceAdapter.loadMoreComplete();
        } else if (user.getOrderType().equals(Constant.TAB_TYPE_MSG)) {
            msgAdapter.loadMoreComplete();
        } else {
            oneSayAdapter.loadMoreComplete();
        }
    }

    @Override
    public void pullMoreNoMore(String... msg) {
        if (user.getOrderType().equals(Constant.TAB_TYPE_LIKE)) {
            sentenceAdapter.loadMoreComplete();
        } else if (user.getOrderType().equals(Constant.TAB_TYPE_MSG)) {
            msgAdapter.loadMoreComplete();
        } else {
            oneSayAdapter.loadMoreComplete();
        }
        customLoadMoreView.setLoadMoreStatus(CustomLoadMoreView.STATUS_END);
    }

    @Override
    public void refreshComplite(String... msg) {
        hFrame.refreshComplete();
//        if (user.getOrderType().equals(Constant.TAB_TYPE_LIKE)) {
//            sentenceAdapter.notifyDataSetChanged();
//        } else if (user.getOrderType().equals(Constant.TAB_TYPE_MSG)) {
//            msgAdapter.notifyDataSetChanged();
//        } else {
//            oneSayAdapter.notifyDataSetChanged();
//        }
        sentenceAdapter.notifyDataSetChanged();
        msgAdapter.notifyDataSetChanged();
        oneSayAdapter.notifyDataSetChanged();
        customLoadMoreView.setLoadMoreStatus(CustomLoadMoreView.STATUS_DEFAULT);
        textNoData.setVisibility(View.GONE);
    }

    @Override
    public void refreshNoData(String... msg) {
        textNoData.setVisibility(View.VISIBLE);
    }
    @Override
    public void allMsgRead() {
        if (msgAdapter.getData()==null||msgAdapter.getData().size()<1){
            textMsgFlag.setVisibility(View.INVISIBLE);
            return;
        }
        for (MsgEntity.ItemsBean itemsBean : msgAdapter.getData()) {
            if (!itemsBean.isIsRead()){
                textMsgFlag.setVisibility(View.VISIBLE);
                return;
            }
        }
        textMsgFlag.setVisibility(View.INVISIBLE);

    }

    @Override
    public void startNextAc(Intent intent, int... type) {
        if (type.length>0){
            startActivityForResult(intent,type[0]);
        }else {
            startActivity(intent);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshHeadView(User user1) {
        initUserView(user1);
    }


    private void initUserView(User myuser) {
        textCity.setText(myuser.getCityName());
        textName.setText(myuser.getUserName());
        if (myuser.getHeadUrl() != null) {
            Glide.with(getContext()).load(Constant.BASE_URL + myuser.getHeadUrl()).error(R.mipmap.pic2).into(imageview);
        } else {
            if (myuser.getHeadUrl_local() != null) {
                try {
                    Glide.with(getContext()).load(new File(myuser.getHeadUrl())).into(imageview);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
